package com.shop.pay.controller;

import com.base.common.entity.PayLog;
import com.base.common.entity.User;
import com.base.common.http.HttpResult;
import com.base.common.utils.UserUtils;
import com.shop.pay.feign.ApiOrderFeign;
import com.shop.pay.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.sun.tools.javac.jvm.ByteCodes.ret;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private PayService payService;

    @Autowired
    private ApiOrderFeign apiOrderFeign;

    /**
     * 创建二维码
     * @return
     */
    @RequestMapping("/createNative")
    public HttpResult createNative(HttpServletRequest request, HttpServletResponse response) {

        /** 根据token得到用户信息，用户名字查询用户支付日志 */
        User user = UserUtils.getUser(request);
        if(user != null ) {

            /** 支付订单日志 */
            PayLog payLog = apiOrderFeign.findPayLogByUserName(user.getId());

            if (payLog != null) {
                try {
                    Map<String, String> ret = payService.createNative(payLog.getOutTradeNo(), String.valueOf(payLog.getTotalFee()));
                    return HttpResult.ok(ret);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return HttpResult.error("创建失败");
    }

    @RequestMapping("/createCode")
    public HttpResult createCode(@RequestParam("outtradeno") String outtradeno, @RequestParam("money") String money){
        Map<String, String> ret = payService.createNative(outtradeno, money);
        return HttpResult.ok(ret);
    }

    /**
     * 查询订单状态
     * @param outtradeno
     * @return
     */
    @RequestMapping("/queryStatus")
    public HttpResult queryStatus(@RequestParam("outtradeno") String outtradeno, HttpServletRequest request, HttpServletResponse response) {

        /** 根据token得到用户信息 */
        User user = UserUtils.getUser(request);

        try {
            //累计=5
            int count=0;
            while (true){
                //累计=5
                Map<String, String> resultMap = payService.queryStatus(outtradeno);
                //获取业务结果  result_code:SUCCESS  成功
                //判断交易状态   trade_state:SUCCESS 交易成功
                //                          REFUND—转入退款  证书
                //                          NOTPAY—未支付
                //                          CLOSED—已关闭
                //                          REVOKED—已撤销（付款码支付）
                //                          USERPAYING--用户支付中（付款码支付）
                //                          PAYERROR--支付失败(其他原因，如银行返回失败)
                String tradeState = resultMap.get("trade_state");
                //SUCCESS:支付成功   跳转到支付成功页面
                if(tradeState.equalsIgnoreCase("SUCCESS")){
                    //修改订单状态   transaction_id
                    String transactionId = resultMap.get("transaction_id");
                    String payTime = resultMap.get("time_end");
                    apiOrderFeign.updateStatus(String.valueOf(user.getId()),transactionId,payTime);
                    return HttpResult.ok("支付成功");
                }else if(tradeState.equalsIgnoreCase("NOTPAY") || tradeState.equalsIgnoreCase("USERPAYING")){
                    //NOTPAY|USERPAYING  继续查询
                    System.out.println("继续查询....");
                    //休眠3秒
                    Thread.sleep(3000);
                    //累加
                    count++;
                    //如果count>=5,超过15秒
                    if(count>=5){
                        //尝试关闭二维码支付->调用腾讯
                        //超时
                        return HttpResult.ok("504");
                    }
                    continue;
                }else if (tradeState.equalsIgnoreCase("CLOSED")){
                    return HttpResult.ok("支付已关闭");
                }else {
                    //其他原因支付失败
                    return HttpResult.error("失败");
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return  null;
    }

    /**
     * 关闭订单
     * @param outtradeno
     * @return
     */
    @RequestMapping("/closePay")
    public HttpResult closePay(@RequestParam("outtradeno") String outtradeno) {
        try {
            Map<String, String> ret = payService.closePay(outtradeno);
            return HttpResult.ok(ret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return HttpResult.error("关闭失败");
    }


}

